<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Api\ApiController;
use App\Utils\ResponseEnum;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\View\Factory;
use Illuminate\Contracts\View\View;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use OSS\Core\OssException;
use OSS\OssClient;

class UploadController extends ApiController
{
    /**
     * 上传提交
     * @param Request $request
     * @return JsonResponse
     */
    public function doUpload(Request $request): JsonResponse
    {
        $data = [];
        $disk = Storage::disk('public');
        foreach ($request->file() as $file) {
            if (!$file->isValid())
                return $this->fail(ResponseEnum::CLIENT_DELETED_ERROR);
            $saveFile = 'rbh'. DIRECTORY_SEPARATOR . date('Ymd') . DIRECTORY_SEPARATOR . uniqid() . '.jpg' ;
            $response = $disk->put($saveFile, file_get_contents($file->getRealPath()));
            $data[] = $saveFile;
        }
        return $this->success($data);
    }

    /**
     * @return Application|Factory|View|\Illuminate\Foundation\Application
     */
    public function upload(): \Illuminate\Foundation\Application|View|Factory|Application
    {
        return view('upload');
    }

    public function oss() {
        try {
            $ossClient = new OssClient(env('OSS_ACCESS_KEY_ID'), env('OSS_ACCESS_KEY_SECRET'), env('OSS_ENDPOINT'));
            $bucketListInfo = $ossClient->listBuckets();
            $bucketList = $bucketListInfo->getBucketList();
            foreach($bucketList as $bucket) {
                print($bucket->getLocation() . "\t" . $bucket->getName() . "\t" . $bucket->getCreateDate() . "\n");
            }
        } catch (OssException $e) {
            print $e->getMessage();
        }
    }
}
